/*
* @Author: Administrator
* @Date:   2018-01-09 15:41:22
* @Last Modified by:   Administrator
* @Last Modified time: 2018-01-09 15:57:43
*/
const multipart = require('connect-multiparty')
const FormData = require('form-data')
const request = require('request')
const fs = require('fs')
const qs = require('qs')
const axios = require('axios')
const handleApi = (app) => {
  app.use('/user_action', require('./user'))
  app.use('/react_wp', function (req, res, next) {
    const headers = {}
    const baseUsl = 'http://jhmaimai.top/react_wp' + req.url
    if (req.session.userToken) {
      headers.Authorization = 'Bearer ' + req.session.userToken
    }
    const config = {
      method: req.method,
      url: baseUsl,
      data: qs.stringify(req.body),
      headers
    }
    axios(config).then(result => {
      res.send(result.data)
    }).catch(next)
  })
  const multipartMiddleware = multipart()
  app.use('/upload', multipartMiddleware, function (req, res, next) {
    // 图片上传api
    const url = 'http://jhmaimai.top/react_wp/wp-json/wp/v2/media'
    // 接受的文件数据
    const files = req.files.fileImg
    const formData = Object.assign(
      {},
      // 非文件数据
      req.body,
      {fileImg: fs.createReadStream(files.path)}
    )
    request.post({url: url,
      formData: formData,
      headers: {
        'Content-Disposition': `attachment; filename=${escape(files.name)}`,
        'Authorization': 'Bearer ' + req.session.userToken
      }}, function (err, httpResponse, body) {
      if (err) {
        return res.send(err)
      }
      res.send(body)
    })
  })
}
module.exports = handleApi
